import type { Router } from "vue-router";
import { SessionStorageService } from "@/hooks/useStorage";
import { useCommonStore } from '@/store/common';

export function createGuard(router: Router) {
  const store = useCommonStore();
  router.beforeEach(async (to, from, next) => {
    const token: string = to.query.userid as string
    const requiresAuth = to.meta && to.meta.requiresAuth
    if (!requiresAuth) {
      next();
      return
    }
    if (token) {
      SessionStorageService.set("token", token);
      next();
    } else {
      const stoken = SessionStorageService.get("token");
      if (stoken) {
        next();
      } else {
        router.push('/not-found')
      }
    }
  });
  router.afterEach((to, from, next) => {
    // 更改titile
    store.saveTitile(to.meta && (to.meta.title as string) || store.title)
    let html = document.querySelector('html')
    if (to.fullPath === '/driving-cabin') {
      if (html) html.style.background = '#9e1806'
    } else {
      if (html) html.style.background = '#fff'
    }
  });
}

